package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.crm.domain.dto.*;
import com.yu.crm.domain.pojo.*;
import com.yu.crm.domain.response.BuildingRep;
import com.yu.crm.mapper.CrmEarlyWarningDiscernAreaMapper;
import com.yu.crm.service.ICrmEarlyWarningDiscernAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxzz.common.config.UserCacheManager;
import com.yxzz.common.helper.DataHelpers;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pan
 * @since 2020-07-01
 */
@Service
public class CrmEarlyWarningDiscernAreaService extends ServiceImpl<CrmEarlyWarningDiscernAreaMapper, CrmEarlyWarningDiscernArea> implements ICrmEarlyWarningDiscernAreaService {

    @Autowired
    UserCacheManager userCacheManager;
    @Autowired
    CrmDeviceService deviceService;

    @Autowired
    CrmPlanService planService;

    public void addOrUpdate(CrmEarlyWarningDiscernArea discernArea){
        //删除原来保存的信息
        Long areaId = discernArea.getAreaId();
        QueryWrapper<CrmEarlyWarningDiscernArea> wrapper = new QueryWrapper<>();
        wrapper.eq("area_id", areaId);
        this.remove(wrapper);
        if(discernArea.getCameraIds()!=null) {
            List<String> cameraIds = discernArea.getCameraIds();
            //保存每一个摄像头信息
            List<CrmEarlyWarningDiscernArea> discernAreas = new ArrayList<>();
            String uuid = UUID.randomUUID().toString();
            for (String str : cameraIds) {
                CrmDevice device = deviceService.getById(str);

                CrmEarlyWarningDiscernArea discernArea1 = new CrmEarlyWarningDiscernArea();
                discernArea1.setCameraId(str);
                discernArea1.setTimeScheme(uuid);
                discernArea1.setCameraName(device.getDeviceName());
                discernArea1.setLocation(discernArea.getLocation());
                discernArea1.setAreaName(discernArea.getAreaName());
                discernArea1.setBuildingId(discernArea.getBuildingId());
                discernArea1.setDescription(discernArea.getDescription());
                discernArea1.setAreaId(discernArea.getAreaId());
                discernArea1.setGmtCreate(LocalDateTime.now());
                discernArea1.setGmtModified(LocalDateTime.now());
                discernAreas.add(discernArea1);
            }
            this.saveBatch(discernAreas);
        }
    }

    @Override
    public IPage<CrmEarlyWarningDiscernArea> list(Page<CrmEarlyWarningDiscernArea> page, Long discernId, String areaName) {
        QueryWrapper<CrmEarlyWarningDiscernArea> wrapper = new QueryWrapper<>();
        wrapper.eq("early_warning_discern_id",discernId);
        if(DataHelpers.isNotEmpty(areaName)) {
            wrapper.like("area_name",areaName);
        }
        return this.page(page,wrapper);
    }

    @Override
    public List<CrmAreaManage> getAllArea() {
        String userId = userCacheManager.getCurrentUser().getUserId();
        return baseMapper.getAllArea(userId);
    }

    @Override
    public List<CrmBuilding> getBuildingByAreaManagerId(Long areaManageId) {
        return baseMapper.getBuildingByAreaManagerId(areaManageId);
    }

    @Override
    public List<CrmDevice> getAllDeviceByAreaBuildingId(Long areaBuildingId,String areaBuildingType) {
        return baseMapper.getAllDeviceByAreaBuildingId(areaBuildingId,areaBuildingType);
    }

    @Override
    public List<CrmDevice> getAllDeviceByPlatformType(String platformType) {
//        String userId = userCacheManager.getCurrentUser().getUserId();
        return baseMapper.getAllDevice(platformType);
    }


    @Override
    public BuildingRep getLocationByDeviceId(Long deviceId, String areaBuildingType) {
        return baseMapper.getLocationByDeviceId(deviceId,areaBuildingType);
    }

    @Override
    public CrmAreaManage getAreaManageByBuildingId(Long buildingId) {
        return baseMapper.getAreaManageByBuildingId(buildingId);
    }


    public static Map<String,String> getWeekDate() {
        Map<String,String> map = new HashMap<String, String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if(dayWeek==1){
            dayWeek = 8;
        }
        System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        Date mondayDate = cal.getTime();
        String weekBegin = sdf.format(mondayDate);
        System.out.println("所在周星期一的日期：" + weekBegin);


        cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();
        String weekEnd = sdf.format(sundayDate);
        System.out.println("所在周星期日的日期：" + weekEnd);

        map.put("mondayDate", weekBegin);
        map.put("sundayDate", weekEnd);
        return map;
    }


    public List<PlanDto> listPlanCamera() {

        List<CrmEarlyWarningDiscernArea> list = this.list();
        List<PlanDto> data = new ArrayList<>();
        if(DataHelpers.isNotEmpty(list)) {
            list.forEach(v -> {
                List<AppScenario> appScenarios = new ArrayList<>();
                AppScenario appScenario = new AppScenario();
                appScenario.setType(Integer.valueOf(v.getAiType()));
                appScenarios.add(appScenario);

                if(DataHelpers.isNotEmpty(v.getEnlarge())) {
                    AppScenario appScenario1 = new AppScenario();
                    appScenario1.setType(3);
                    appScenario1.setParam(new Param(Integer.valueOf(v.getEnlarge())));
                    appScenarios.add(appScenario1);
                }

                if(DataHelpers.isNotEmpty(v.getPollingPlan())) {
                    AppScenario appScenario1 = new AppScenario();
                    appScenario1.setType(Integer.valueOf(v.getPollingPlan()));
                    appScenarios.add(appScenario1);
                }
                data.add(new PlanDto(v.getCameraId(), v.getTimeScheme(), appScenarios));
            });
        }
        return data.stream().collect( collectingAndThen( toCollection(() -> new TreeSet<>(Comparator.comparing(PlanDto::getCameraId))), ArrayList::new) );
//        return data;
    }




    public List<PlanInfoDto2> planInfo(long timestamp) {
        List<CrmPlan> list = planService.list();
        List<PlanInfoDto2> data = new ArrayList<>();
        Date time = new Date(timestamp);
        if(list != null && list.size() >0) {
            list.forEach(v->{
                PlanInfoDto2 planInfoDto = null;
                if(time.getTime() == 0){
                    if(v.getPlanType().equals(1)) { //时间范围
                        planInfoDto = new PlanInfoDto(v.getId().toString(),v.getPlanFrom(),v.getPlanTo(),DateFormatUtils.format(v.getStartTime(),"yyyy-MM-dd HH:mm:ss"),
                                DateFormatUtils.format(v.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                    }else if(v.getPlanType().equals(0)){
                        planInfoDto =  new PlanInfoDto2(v.getId().toString(), v.getPlanFrom(),v.getPlanTo());
                    }
                } else {
                    if(v.getPlanType().equals(1)  && time.after(v.getStartTime()) && time.before(v.getEndTime())) { //时间范围
                        planInfoDto = new PlanInfoDto(v.getId().toString(),v.getPlanFrom(),v.getPlanTo(),DateFormatUtils.format(v.getStartTime(),"yyyy-MM-dd HH:mm:ss"),
                                DateFormatUtils.format(v.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                    }else if(v.getPlanType().equals(0)) { //周一到周日
                        planInfoDto =  new PlanInfoDto2(v.getId().toString(), v.getPlanFrom(),v.getPlanTo());
                    }
                }
                data.add(planInfoDto);
            });
        }
        return data;
    }
}
